package com.example.fireassistant_server.controller;

import com.example.fireassistant_server.dto.company.CompanyCreateRequest;
import com.example.fireassistant_server.dto.company.CompanySearchFilter;
import com.example.fireassistant_server.dto.company.CompanyUpdateRequest;
import com.example.fireassistant_server.dto.hydrant.FireHydrantUpdateRequest;
import com.example.fireassistant_server.dto.user.UserCreateRequest;
import com.example.fireassistant_server.dto.user.UserSearchFilter;
import com.example.fireassistant_server.mapper.CompanyMapper;
import com.example.fireassistant_server.service.CompanyService;
import com.example.fireassistant_server.vo.CompanyVo;
import com.example.fireassistant_server.vo.FireHydrantVo;
import com.example.fireassistant_server.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/company")
public class CompanyController {

    CompanyMapper companyMapper;

    CompanyService companyService;

    // 创建单位 需要的参数为(province, cityName,companyName, latitude, longitude ,radius);有权限要求
    @RequestMapping(method = RequestMethod.POST)
    @PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
    CompanyVo create(@Validated @RequestBody CompanyCreateRequest companyCreateRequest) {
        return companyMapper.toVo(companyService.create(companyCreateRequest));
    }

    //按条件查询单位的功能;对所有人开放
    //@RequestBody 不是通过路径传参
    @PostMapping("/search")
    Page<CompanyVo> search(@Validated @RequestBody CompanySearchFilter companySearchFilter) {
        return companyService.search(companySearchFilter).map(companyMapper::toVo);
    }

    //根据id 查询单位
    @GetMapping("/{id}")
    CompanyVo get(@PathVariable String id) {
        return companyMapper.toVo(companyMapper.toDto(companyService.get(id)));
    }

    // 根据id删除单位；删除单位时必须先删除单位下所有user；外键指向的是主表，需删除从表，再删除主表；谨慎使用；有权限要求
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
    void delete(@PathVariable String id) {
        companyService.delete(id);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ROLE_SUPER_ADMIN') or hasRole('ROLE_STATION_ADMIN')")
    CompanyVo update(@PathVariable String id,
                         @Validated @RequestBody CompanyUpdateRequest companyUpdateRequest) {
        return companyMapper.toVo(companyService.update(id,companyUpdateRequest));
    }

    @Autowired
    public void setCompanyMapper(CompanyMapper companyMapper) {
        this.companyMapper = companyMapper;
    }

    @Autowired
    public void setCompanyService(CompanyService companyService) {
        this.companyService = companyService;
    }
}
